<template>
	<div class="address_edit">
		<van-nav-bar :title="pageTitle" @click-left="goBack" />
		<van-address-edit :area-list="areaList" :address-info="addressInfo" show-postal show-delete show-set-default
			:area-columns-placeholder="['请选择省', '请选择市', '请选择区/县']" @save="onSave" @delete="onDelete">
			<div slot="default" class="tips">
				提醒：每次下单时会优先使用该地址，但实际下单地址会根据您购物时切换的地区进行智能判断，请在下单时仔细确认。
			</div>
		</van-address-edit>
		<van-loading v-if="isLoading" />
	</div>
</template>

<script>
	import {
		showToast
	} from 'vant';
	import {
		areaList
	} from "@vant/area-data";
	import {
		getAddressDetailByIdAPI,
		saveAddressAPI,
		deleteAddressByIdAPI
	} from "@/api/address.js";

	export default {
		props: ["id"],
		data() {
			return {
				areaList,
				addressInfo: {
					id: "",
					name: "",
					tel: "",
					province: "",
					city: "",
					county: "",
					areaCode: "",
					postalCode: "",
					addressDetail: "",
					isDefault: false
				},
				isLoading: false
			};
		},
		computed: {
			pageTitle() {
				return this.id === "new" ? "新增地址" : "编辑地址";
			}
		},
		created() {
			// 区分新增和编辑模式
			if (this.id === "new") {
				this.resetForm(); // 新增模式：初始化空表单
			} else {
				this.getAddressDetail(); // 编辑模式：加载已有地址
			}
		},
		methods: {
			async getAddressDetail() {
				if (!this.id) return; // 防御性编程，确保id存在

				try {
					const result = await getAddressDetailByIdAPI(this.id);
					// 将API返回的数据映射到表单数据
					this.addressInfo = {
						id: result.data.id,
						name: result.data.name,
						tel: result.data.tel,
						province: result.data.province,
						city: result.data.city,
						county: result.data.county,
						areaCode: result.data.area_code,
						postalCode: result.data.postal_code,
						addressDetail: result.data.address_detail,
						isDefault: result.data.is_default === 1
					};
				} catch (error) {
					console.error('获取地址详情失败:', error);
					showToast('获取地址详情失败，已切换至新增模式');
					this.resetForm(); // 出错时也初始化空表单，允许用户创建新地址
				}
			},

			resetForm() {
				// 初始化空表单
				this.addressInfo = {
					id: "", // 新增时不需要id
					name: "",
					tel: "",
					province: "",
					city: "",
					county: "",
					areaCode: "", // 确保初始化为空
					postalCode: "",
					addressDetail: "",
					isDefault: false
				};
			},

			onSave(content) {
				if (!content.name || !content.tel || !content.addressDetail || !content.areaCode) {
					showToast('姓名、电话、详细地址、地区编码不能为空');
					return;
				}

				// 根据是否有id决定调用新增还是编辑API
				// 注意：你的API通过同一个接口处理新增和编辑，根据id是否存在区分
				const addressParams = this.formatAddressParams(content);

				this.handleAsyncOperation(() => saveAddressAPI(addressParams), '保存地址成功', '保存地址失败');
			},

			onDelete(content) {
				const id = content.id;
				if (!id) return;

				this.handleAsyncOperation(() => deleteAddressByIdAPI(id), '删除地址成功', '删除地址失败');
			},

			handleAsyncOperation(apiCall, successMsg, errorMsg) {
				this.isLoading = true;
				apiCall()
					.then(result => {
						showToast(result.msg || successMsg);
						this.goBack();
					})
					.catch(error => {
						console.error(errorMsg, error);
						showToast(errorMsg + '，请稍后重试');
					})
					.finally(() => {
						this.isLoading = false;
					});
			},

			formatAddressParams(content) {
				return {
					id: this.id === "new" ? "" : content.id, // 新增时id为空，编辑时保留id
					name: content.name,
					tel: content.tel,
					province: content.province,
					city: content.city,
					county: content.county,
					area_code: content.areaCode,
					postal_code: content.postalCode,
					address_detail: content.addressDetail,
					is_default: content.isDefault ? 1 : 0
				};
			},

			goBack() {
				setTimeout(() => {
					this.$router.go(-1);
				}, 1000);
			}
		}
	};
</script>

<style scoped lang="less">
	@bgColor: #f0f0f0;
	@mainColor: #e74c3c;
	@textColor: #333;

	.address_edit {
		background-color: @bgColor;
		padding: 15px;
		border-radius: 10px;
		box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1);

		.van-address-edit {
			border: none;
			border-radius: 8px;
			background-color: #fff;

			.van-address-edit__buttons {
				margin-top: 20px;
				text-align: right;

				.van-button--danger {
					background: @mainColor;
					border-color: @mainColor;
					border-radius: 5px;
					padding: 8px 16px;
					font-size: 14px;
				}
			}

			.tips {
				padding: 12px;
				font-size: 14px;
				color: @mainColor;
				border-top: 1px solid #e0e0e0;
				border-bottom: 1px solid #e0e0e0;
				margin-bottom: 10px;
			}

			.van-address-edit__content {
				color: @textColor;
				font-size: 14px;
			}
		}
	}
</style>